#pragma once

#include<iostream>
#include<fstream>
#include "contacts.pb.h"
#include "ContactException.h"

using namespace std;

#define TEXT_NAME "../contacts/contacts.txt"

class ContactsMapper {
public:
    void selectContacts(contacts::Contacts* contacts) const
    {
        std::fstream input(TEXT_NAME, ios::in | ios::binary);

        if (!input) {
            cout << "---> (ContactsMapper::selectContacts) " << TEXT_NAME << ": File not found.  Creating a new file." << endl;
        }
        else if (!contacts->ParseFromIstream(&input)) {
            input.close();
            throw ContactException("(ContactsMapper::selectContacts) Failed to parse contacts.");
        }
        input.close();
    }

    void insertContacts(contacts::Contacts& contacts) const
    {
        std::fstream output(TEXT_NAME, ios::out | ios::trunc | ios::binary);

        if (!contacts.SerializeToOstream(&output)) {
            output.close();
            throw ContactException("(ContactsMapper::insertContacts) Failed to write contacts.");
        }
        output.close();
    }
};

